import { Modal, Form, message } from 'antd';
import ProForm, { ProFormText, ProFormRadio } from '@ant-design/pro-form';
import { save, update } from '@/services/system/resource/button';
import {SystemMenuTreeSelect} from '@/components/system/resource'

const SystemButtonForm = (props) => {

  const [form] = Form.useForm();
  const { formVisible, onSubmit, onCancel, values } = props;

  const saveHandle = async (formValue) => {
    const data = await save(formValue);

    if (data.success) message.success('新建按钮权限成功!');
    else message.error('新建按钮权限失败!');
  };

  const updateHandle = async (formValue) => {
    const data = await update(formValue);

    if (data.success) message.success('修改按钮权限成功!');
    else message.error('修改按钮权限失败!');
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...values, ...fieldsValue};

    if (formValue.id) await updateHandle(formValue);
    else await saveHandle(formValue);

    onSubmit();
  }

  return (
    <Modal
      destroyOnClose
      title={values.id ? '修改按钮权限信息' : '新增按钮权限信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={values} 
        form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        <Form.Item label="上级资源" name="parentId" rules={[{ required: true, message: '请选择上级资源信息!' }]}>
          <SystemMenuTreeSelect disabledKey={values.id}/>
        </Form.Item>
        <ProFormText  name="name" label="按钮名称" rules={[{ required: true, message: '请输入按钮名称!' }, {max: 50, message: '按钮名称过长!'}]} />
        <ProFormText  name="permission" label="权限标识" rules={[{max: 50, message: '权限标识过长!'}]}/>
        <ProFormText  name="url" label="请求链接" rules={[{ required: true, message: '请输入请求链接!' }, {max: 200, message: '请求链接过长!'}]}/>
        <ProFormRadio.Group  
          name="method" label="请求方法" 
          options={[
            { value: 'Get', label: 'Get', },
            { value: 'Post', label: 'Post', },
            { value: 'Put', label: 'Put', },
            { value: 'Delete', label: 'Delete', },
          ]}
          initialValue="Get"
          rules={[{ required: true, message: '请选择请求方法!' }]}
        />
      </ProForm>
    </Modal>
  );
}

export default SystemButtonForm;